<?php
namespace Services\Request;
use Services\Log\LogService;
use Think\Log;

class TemplateRequest extends BaseRequest
{
    public $logType = 'TemplateRequest';
    /**
     * 接口基础url
     * 若实现了setBaseUri()方法,此处可不定义,两者二选一即可
     * @var string
     */
    public $baseUri;

    /**
     * 自定义业务侧响应成功状态码
     * 默认0表示成功,非0则失败
     * 可根据对接的三方情况相互约定成功响应的code值
     * @var int
     */
    public $successCode = 0;

    /**
     * 请求超时时间,单位:s
     * @var int
     */
    public $timeout = 10;

    /**
     * 是否开启调试 true:开启 false:关闭
     * @var bool
     */
    public $debug = false;

    /**
     * 是否自动加签, true:是 false:否
     * 开启的话,接口请求默认会追加sign参数进行透传
     * @var bool
     */
    public $sign = false;


    //请求接口path
    public const API = [
        'demo' => 'wxapp.php/test/requestResultTest.html'
    ];

    public function __construct()
    {
        $this->initBaseUri();
    }

    /**
     * 定义请求三方接口的基础url
     * @return string
     */
    public function setBaseUri(): string
    {
        return 'https://hsg001.jieyou.work/';
    }

    public function initBaseUri()
    {
        parent::initBaseUri();
    }

    /**
     * 测试接口
     * @param $options
     * @return mixed
     * @throws \Exception
     */
    public function demo($options = []){
        return $this->buildRequest(self::API['demo'],[],'json');
    }



    /**
     * 重写父类的响应处理,针对不同的三方,则自定义最终响应结果该如何处理
     * @return void
     * @throws \Exception
     */
    public function parseResponse()
    {
        try {
            $result = $this->getContent();
            if (empty($result)) {
                throw new \Exception('公众号请求失败');
            }
            $responseCode = arr_get($result, 'code', -1);
//            $error = Arr::get($result, 'ResponseMetadata.Error', []);
//            if ($error) {
//                $codeN = Arr::get($error, 'CodeN', 0);
//                $code = Arr::get($error, 'Code', '');
//                throw new ByteDanceExceptions("{$codeN}:{$code}");
//            }
            if ($responseCode == 1) {
                $this->content = $result;
            }
        } catch (\Throwable $exception) {
            LogService::write([
                'base_uri' => $this->getBaseUri(),
                'url' => $this->getUri(),
                'params' => $this->getParams(),
                'method' => $this->getMethod(),
                'body' => $this->getBody(),
                'content' => $this->getContent(),
                'message' => $exception->getMessage(),
            ],'请求异常',Log::ERR);
            throw $exception;
        }
    }
}
